class Api::V1::TopicsController < Api::V1::BaseController
  def index
    @topics = Topic.where(sale_or_buy: params[:sale_or_buy], state: :checked).order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def show
    @topic = Topic.find params[:id]
  end

  def create
    @topic = Topic.new topic_params
    @topic.user_id = @current_user.id
    @topic.state = :pending
    if @topic.save
      render json: { result: true, message: '保存成功.', data: { id: @topic.id } }, status: :ok
    else
      render json: { result: false, message: '保存失败.' }, status: :ok
    end
  end

  def update
    @topic = Topic.find params[:id]
    if @topic.user_id == @current_user.id
      if @topic.update topic_params
        render json: { result: true, message: '更新成功.' }, status: :ok
      else
        render json: { result: false, message: '更新失败.' }, status: :ok
      end
    else
      render json: { result: false, message: '无权操作.' }, status: :ok
    end
  end
  
  def destroy
    @topic = Topic.find params[:id]
    if @topic.user_id == @current_user.id
      if @topic.destroy
        render json: { result: true, message: '删除成功.' }, status: :ok
      else
        render json: { result: false, message: '删除失败.' }, status: :ok
      end
    else
      render json: { result: false, message: '无权操作.' }, status: :ok
    end
  end

  private

  def topic_params
    params.require(:topic).permit(:sale_or_buy, :name, :quantity, :title, :price, :phone, :province_id, :city_id, :district_id, :description, :user_id, :state, topic_picture_ids: [])
  end
end
